﻿using UnityEngine;
using System;
using System.Collections;
using UniLua;
using TCG.FFI;

namespace TCG
{
	public class LuaInterface
    {
        public void Initialize (string entryluaPath)
        {
            // 初始化lua
            m_luaState = LuaAPI.NewState ();
            m_luaState.L_OpenLibs ();

            // 导出注册库功能
            m_luaState.L_RequireF (FFILibRegisterLib.LIB_NAME, FFILibRegisterLib.OpenLib, false);
            m_luaState.Pop (1);

            // 加载lua入口文件
            ThreadStatus status = m_luaState.L_DoFile (entryluaPath);
            if (status != ThreadStatus.LUA_OK)
            {
                throw new Exception (m_luaState.ToString (-1));
            }

            if (!m_luaState.IsTable (-1))
            {
                throw new Exception ("main lua return value is not a table.");
            }

            // 加载基本回调
            m_lua_methodRef_start = LuaTools.RefLuaFunction (m_luaState, -1, "start");
			m_lua_methodRef_update = LuaTools.RefLuaFunction (m_luaState, -1, "update");

            // 将栈顶的table弹出
            m_luaState.Pop (1);
        }

		public void Start ()
		{
			LuaTools.CallLuaRefFunction (m_luaState, m_lua_methodRef_start, 0, 0, 0);
		}
		
		public void Update ()
		{
			m_luaState.PushNumber (Time.time);
			m_luaState.PushNumber (Time.deltaTime);
			LuaTools.CallLuaRefFunction (m_luaState, m_lua_methodRef_update, 2, 0, 0);
		}

		public ILuaState luaState
		{
			get { return m_luaState; }
		}

        ILuaState m_luaState = null;

        int m_lua_methodRef_start;
        int m_lua_methodRef_update;
    }
}
